package com.feiyue.learning.advance.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Java NIO 的 Channel 类
 * @author  feiyue
 * @date  2020/4/18
 */
public class ChannelDemo {

    private static final String SRC_PATH = "C:\\Users\\zhou.xm\\Desktop\\get.json";
    private static final String DEST_PATH = "C:\\Users\\zhou.xm\\Desktop\\dest.json";

    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream(SRC_PATH);

        FileChannel inChannel = fis.getChannel();
        ByteBuffer byteBur = ByteBuffer.allocate(1024);
        int length = -1;

        // inChannel 输入通道, 输出数据到缓存中（针对通道是读取，针对缓冲区是写入）
        while ((length = inChannel.read(byteBur)) != -1) {
            System.out.println("读取的字节数：" + length);
        }
        inChannel.close();

        byteBur.flip();
        FileOutputStream fos = new FileOutputStream(DEST_PATH);
        FileChannel outChannel = fos.getChannel();
        int outLength = 0;

        // outChannel 输出通道, 输出到硬盘（针对通道是写入，针对缓冲区是读入）
        while ((outLength = outChannel.write(byteBur)) != 0) {
            System.out.println("写入的字节数：" + outLength);
        }
        outChannel.force(true);
        outChannel.close();
    }
}
